package com.stylefeng.guns.modular.model.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.model.model.BusGps;
import com.stylefeng.guns.modular.model.service.*;
import com.stylefeng.guns.modular.model.utils.HttpRequest;
import com.stylefeng.guns.modular.system.model.*;
import io.swagger.models.auth.In;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * model控制器
 *
 * @author fengshuonan
 * @Date 2018-08-01 19:01:25
 */
@Controller
@RequestMapping("/actualRoute")
public class ActualRouteController extends BaseController {

    private String PREFIX = "/model/actualRoute/";
    @Autowired
    private ICarSiteService carSiteService;

    @Autowired
    IOrderService orderService;
    @Autowired
    private IActualRouteService actualRouteService;

    @Autowired
    ITicketNumService ticketNumService;
    @Autowired
    IActivityCentreService activityCentreService;
    @Autowired
    IActivityService activityService;
    @Autowired
    ITicketPriceService ticketPriceService;

    @Autowired
    IStaActCentreService staActCentreService;


    /*
    2018-8-2 得到路线字符串
     */
    @RequestMapping("/actuallist")
    @ResponseBody
    public Object actuallist(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        List<ActualRoute> list = actualRouteService.linelist();
        for (int i = 0; i < list.size(); i++) {
            ActualRoute route = list.get(i);
            String carsiteids = list.get(i).getCarSiteids();

            //用，把字符串分割成字符串数组
            String[] arr = carsiteids.split(",");
            //定义一个和字符串数组一样大小的int数组
            int[] arr2 = new int[arr.length];
            //把字符串数组中的值，转换为int类型，放入int数组
            List listact = new ArrayList();
            List liststr = new ArrayList();
            StringBuffer str = new StringBuffer();
            StringBuffer str2 = new StringBuffer();
            String array = "[";
            for (int n = 0; n < arr.length; n++) {
//                arr2[n]=Integer.parseInt(arr[n]);
//                int carsiteid=arr2[n];
                String carsiteid2 = arr[n];
                if (carsiteid2.length()>0) {
                    CarSite c = carSiteService.querycarsite(carsiteid2);
//                route.getSites().add(c);
                    String lot = c.getLongitude();
                    String lat = c.getLatitude();
                    float lote = Float.valueOf(lot);
                    float late = Float.valueOf(lat);
                    String json = "{";
                    json += lote;
                    json += "," + late + "}";
                    array += json + ",";
                    str.append(lote);
                    str.append(",");
                    str.append(late);
                    str.append(";");
                }
            }
            route.setPoints(str.substring(0, str.length() - 1));
            route.setSitePionts(array.substring(0, array.length() - 1) + "]");
//            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(route));
//            jsonObject.put("sitePoints", str.substring(0, str.length() - 1));
//            array.add(jsonObject);
//            str2.append("{");
//            str2.append(str.substring(0, str.length() - 1));
//            str2.append("}");

//            JSONObject json=new JSONObject();
//			json.accumulate("luxian", listact);

//            System.out.println(i);
        }
//        Writer out = response.getWriter();
////            out.write(JSON.toJSONString(listact));
//        out.write(array.toJSONString());
        return list;
    }
//ksjdflkdslkflkdsf

    @RequestMapping("actualNumOrder")
    @ResponseBody
    public Object actualnum(@RequestParam("lineid")Integer lineid,@RequestParam("userId")Integer userId){
        Map<String, Object> returnMap = new ConcurrentHashMap<String, Object>();
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdfdate = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
        Date date1 = calendar.getTime();

        String getondate=sdfdate.format(date1);
        Order order=orderService.selcetByUserid(userId,1);
        ActivityCentre activityCentre=activityCentreService.selectByActityid(1,userId);
        TicketPrice ticketPrice=ticketPriceService.selectPriceByLineId(lineid);
        TicketNum ticketNum = ticketNumService.getTicketnum(lineid, getondate);
        String  ticketyuanprice=ticketPrice.getTicketPrice();
        float original= Float.valueOf(ticketyuanprice);

        float originalPrice=original/100;//得到实际的价格

        ActualRoute actualRoute=actualRouteService.selectById(lineid);
        String upid =null;
        String endid =null;
        String upname=null;
        String endname=null;
        String uptime=null;
        String endtime=null;
        if (actualRoute!=null) {
            String ids = actualRoute.getCarSiteids();
            upid = ids.substring(0, 1);//H
            endid = ids.substring(ids.length() - 1);//d
           CarSite carSite= carSiteService.selectById(upid);
           upname=carSite.getSitename();
           CarSite carSite1=carSiteService.selectById(endid);
           endname=carSite1.getSitename();
           StaActCentre staActCentre=staActCentreService.selcetstaact(lineid,Integer.valueOf(upid));
           StaActCentre staActCentre1=staActCentreService.selcetstaact(lineid,Integer.valueOf(endid));
           uptime=staActCentre.getCarCometime();
           endtime=staActCentre1.getCarCometime();
        }
//            ActivityCentre activityCentre = activityCentreService.selectByActityUserid(lineid, userId);
        Activity activity = activityService.selectById(activityCentre.getActivityid());
        float  price=activity.getPrice().floatValue();  //需要测一下精确度

        if (order==null) {
            if (ticketNum==null) {
                float surplusprice=originalPrice-price;
                int   scale  =   2;//设置位数
                int   roundingMode  =  4;//表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
                BigDecimal bd  =   new  BigDecimal((double)surplusprice);
                bd   =  bd.setScale(scale,roundingMode);
                surplusprice   =  bd.floatValue();
                returnMap.put("ticketnum", 45);
                returnMap.put("activityid", activityCentre.getActivityid());
                returnMap.put("favorablePrice", activity.getPrice());
                returnMap.put("originalPrice", originalPrice);
                returnMap.put("surplusprice", surplusprice);
                returnMap.put("upname", upname);
                returnMap.put("endname", endname);
                returnMap.put("uptime", uptime);
                returnMap.put("endtime", endtime);
            }else {
                float surplusprice=originalPrice-price;
                int   scale  =   2;//设置位数
                int   roundingMode  =  4;//表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
                BigDecimal bd  =   new  BigDecimal((double)surplusprice);
                bd   =  bd.setScale(scale,roundingMode);
                surplusprice   =  bd.floatValue();
                returnMap.put("ticketnum", ticketNum.getRemainingnum());
                returnMap.put("activityid", activityCentre.getActivityid());
                returnMap.put("favorablePrice", activity.getPrice());
                returnMap.put("originalPrice", originalPrice);
                returnMap.put("surplusprice", surplusprice);
                returnMap.put("upname", upname);
                returnMap.put("endname", endname);
                returnMap.put("uptime", uptime);
                returnMap.put("endtime", endtime);
            }
        }else{
            if (ticketNum==null){
                returnMap.put("ticketnum", 45);
                returnMap.put("originalPrice",originalPrice);
                returnMap.put("favorablePrice", 0);
                returnMap.put("surplusprice", originalPrice);
                returnMap.put("upname", upname);
                returnMap.put("endname", endname);
                returnMap.put("uptime", uptime);
                returnMap.put("endtime", endtime);
            }else {
                returnMap.put("ticketnum", ticketNum.getRemainingnum());
                returnMap.put("originalPrice",originalPrice);
                returnMap.put("favorablePrice", 0);
                returnMap.put("surplusprice", originalPrice);
                returnMap.put("upname", upname);
                returnMap.put("endname", endname);
                returnMap.put("uptime", uptime);
                returnMap.put("endtime", endtime);
            }
        }
        return  returnMap;
    }


    /**
     * 得到公交详细信息（站点，路线名称，时间）
     */
    @RequestMapping("linelist")
    public String linelist(HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        try {
            String linename = "北站-海信创智谷";
            List<CarSite> list = carSiteService.carlinelist(linename);
            Writer out = response.getWriter();
            out.write(JSON.toJSONString(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * ticketnum 统计剩余票数  通过ticketdate  购票时间   ticketdate 是order的getontime
     *
     */

    /**
     * 跳转到model首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "actualRoute.html";
    }

    /**
     * 跳转到添加model
     */
    @RequestMapping("/actualRoute_add")
    public String actualRouteAdd() {
        return PREFIX + "actualRoute_add.html";
    }

    @RequestMapping("/actual")
    public String actual(HttpServletResponse response, HttpServletRequest request, Model model) {
        response.setContentType("text/html;charset=utf-8");
        List<CarSite> listcar = carSiteService.selectsite();
        model.addAttribute("lists", listcar);
        return PREFIX + "actual.html";
    }

    /*
          所有站点信息
         */
    @RequestMapping("site")
    public Object site(HttpServletResponse response, HttpServletRequest request, Model model) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        List<CarSite> listcar = carSiteService.selectsite();
        model.addAttribute("lists", listcar);
        listcar.get(0).getSitename();
        Writer out = response.getWriter();
        out.write(JSON.toJSONString(listcar));
        return null;
    }

    /**
     * 跳转到修改model
     */
    @RequestMapping("/actualRoute_update/{actualRouteId}")
    public String actualRouteUpdate(@PathVariable Integer actualRouteId, Model model) {
        ActualRoute actualRoute = actualRouteService.selectById(actualRouteId);
        model.addAttribute("item", actualRoute);
        LogObjectHolder.me().set(actualRoute);
        return PREFIX + "actualRoute_edit.html";
    }

    /**
     * 获取model列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return actualRouteService.selectList(null);
    }

    /**
     * 新增model
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ActualRoute actualRoute) {
        actualRouteService.insert(actualRoute);
        return SUCCESS_TIP;
    }

    /**
     * 删除model
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer actualRouteId) {
        actualRouteService.deleteById(actualRouteId);
        return SUCCESS_TIP;
    }

    /**
     * 修改model
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ActualRoute actualRoute) {
        actualRouteService.updateById(actualRoute);
        return SUCCESS_TIP;
    }

    /**
     * model详情
     */
    @RequestMapping(value = "/detail/{actualRouteId}")
    @ResponseBody
    public Object detail(@PathVariable("actualRouteId") Integer actualRouteId) {
        return actualRouteService.selectById(actualRouteId);
    }

    /**
     * GPS位置信息
     *
     *
     * 建gps表  要和车辆相对应  灵活性
     *
     * @return
     */
    @RequestMapping(value = "/gps")
    @ResponseBody
    public Object busGpsLocation(@RequestParam(value = "lineId", required = false) Integer lineid) {
        String gpsResult = HttpRequest.sendGet("http://www.zyhgps.com/api/Tracking.aspx", "sn=391518056307570&mapType=google&key=OUCHUANG20170602A009");
        BusGps busGps = JSONObject.parseObject(gpsResult, BusGps.class);
        return busGps;
    }
}
